package com.yunhai.ucenter.service.impl;

import com.yunhai.ucenter.service.CaptchaService;
import com.yunhai.ucenter.service.SysUserService;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

// CaptchaService.java
@Service
public class CaptchaServiceImpl implements CaptchaService {
    private static final String CAPTCHA_PREFIX = "captcha:";
    private static final long CAPTCHA_EXPIRE = 5 * 60; // 5分钟

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 生成并发送验证码
     */
    public String generateAndSendCaptcha(String phone) throws Exception {

        // 生成6位随机验证码
        String captcha = RandomStringUtils.randomNumeric(6);

        // 存储到Redis，设置5分钟过期
        redisTemplate.opsForValue().set(
                CAPTCHA_PREFIX + phone,
                captcha,
                CAPTCHA_EXPIRE,
                TimeUnit.SECONDS
        );

        // 模拟发送短信验证码（实际项目中调用短信服务API）
        System.out.println("发送验证码到手机号 " + phone + ": " + captcha);
        return captcha;

    }

    /**
     * 验证验证码
     */
    public boolean verifyCaptcha(String phone, String captcha) {
        String storedCaptcha = redisTemplate.opsForValue().get(CAPTCHA_PREFIX + phone);
        if( storedCaptcha == null ){
            return false;
        }
        return captcha.equals(storedCaptcha);
    }
}